package com.zw.blog.util;

import com.zw.blog.exception.NotFoundException;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

public class UploadUtils {


    public static final String BLOG_IMAGES_PATH = "/images/blogImages/";

    public static final String EDITOR_IMAGES_PATH = "editorImages/";

    public static final String ABSOLUTE_BLOG_IMAGES_PATH = System.getProperty("user.dir") + "/static" + BLOG_IMAGES_PATH;

    /**
     * 得到项目的class目录下的BlogImages文件夹绝对路径
     */
    /*public static String getAbsoluteBlogImagesPath() {
        *//*try {

            *//**//*File upload = new File(path.getAbsolutePath(), "static" + BLOG_IMAGES_PATH);
            if (!upload.exists()) {
                upload.mkdir();
            }*//**//*
            return ResourceUtils.getURL("classpath:").getPath() + "static" + BLOG_IMAGES_PATH;
        } catch (FileNotFoundException e) {
            throw new RuntimeException("类文件夹没生成！");
        }*//*
            File path = new File(System.getProperty("user.dir"), "static" + BLOG_IMAGES_PATH);
            if (!path.exists()) path.mkdirs();
            return path.getPath() + "/";
    }*/

    /**
     * 随机生成UUID，防止图片重名
     * @return UUID
     */
    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 绕过反爬机制，（503），图片下载
     * @param url 图片url链接
     * @return 建立的url连接
     */
    private static URLConnection getURLConnection(String url) throws IOException {
        URL imageURL = new URL(url);
        URLConnection urlConnection = imageURL.openConnection(); //此时没有连接，是待连接状态
        urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 compatible; MSIE 5.0;Windows NT; DigExt)");
        urlConnection.setConnectTimeout(20000);
        return urlConnection;
    }

    /**
     * 获得的content-type是image/jpeg这种格式，转换成jpeg
     */
    private static String getHttpType(String contentType) {
        return contentType.substring(contentType.lastIndexOf("/") + 1);
    }

    public static String getLocalType(String localFileName) {
        return localFileName.substring(localFileName.lastIndexOf(".") + 1);
    }

    /**
     *
     * @param rootPath 文件输出根路径
     * @param dir 具体的文件夹名（blogImages/editorImages)，方便生成文件映射路径
     * @param fileName 文件名
     * @param in 输入流
     * @return 文件在spring中的映射地址（/images/...)
     */
    public static String outputFile(String rootPath, String dir, String fileName, InputStream in) throws IOException {
        byte[] bs = new byte[1024];
        int len;
        OutputStream out = new FileOutputStream(rootPath + fileName);
        while ((len = in.read(bs)) != -1) {
            out.write(bs, 0, len);
        }
        return dir + fileName;
    }

    public static String uploadHttpImage(String url) throws IOException {
        URLConnection connection = getURLConnection(url);
        String contentType = connection.getContentType();
        if (contentType == null) return("ERROR!图片请求失败！刷新或者下载到本地！");
        if (connection.getContentLengthLong() > 1024 * 1024 * 6) {
            return "ERROR!图像超过了6M，太大了!";
        }
        String type = getHttpType(contentType);
        String fileName =  getUUID() + "." + type;
        InputStream in = connection.getInputStream();
        return outputFile(ABSOLUTE_BLOG_IMAGES_PATH, BLOG_IMAGES_PATH, fileName, in);
    }

    public static String uploadLocalImage(String localFileName, InputStream in) throws IOException {
        //InputStream in = fileContent.getInputStream();
        String type = getLocalType(localFileName);
        String fileName =  getUUID() + "." + type;
        return outputFile(ABSOLUTE_BLOG_IMAGES_PATH, BLOG_IMAGES_PATH, fileName, in);
    }
}
